<template>
    <div class="map-view">
        <slot name="header"></slot>
        <div id="MapContainer"></div>
        <slot name="footer" :clear="clear" :fit="fitView"></slot>
    </div>
</template>

<script>
window._AMapSecurityConfig = {
    securityJsCode: "32a4b48bc5bcacf85e63ef0b5d767056", //开启地图安全密钥
};
import AMapLoader from "@amap/amap-jsapi-loader";
var mUrl = 'assets/mapEle/';
var done = false;
export default {
    name: 'ZMap',
    props: {
        initConfig: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            map: null,
            contextMenu: null,
            infoWindow: null,
            markerType: {
                pink: require(`@/${mUrl}marker-pink.svg`),
                red: require(`@/${mUrl}marker-red.svg`),
                green: require(`@/${mUrl}marker-green.svg`),
                blue: require(`@/${mUrl}marker-blue.svg`),
                I1: require(`@/${mUrl}indexMarker1.png`),
                I2: require(`@/${mUrl}indexMarker2.png`),
                I3: require(`@/${mUrl}indexMarker3.png`),
                I4: require(`@/${mUrl}indexMarker4.png`),
            }
        }
    },
    created() {
        let { initConfig: { defaultStyle } } = this;
        for (let k in defaultStyle) {
            this[k] = defaultStyle[k];
        }
    },
    mounted() {
        let { isAsync = false } = this.initConfig;
        if (isAsync) return;
        this.initMap();
    },
    beforeDestroy() {
        this.destroy();
        this.map = null;
    },
    methods: {
        // 由于地图加载时间难以确定，并且会带有缓存，初始加载和后续加载时间不同
        // 因此初始化需要外部手动执行，并且用Promise处理。
        // 保证初始化所需的内容加载完了再进行操作
        initMap() {
            let { initMap, plugins = [] } = this.initConfig;
            return new Promise((resolve, reject) => {
                AMapLoader.load({
                    key: "e637a3bcc77d3d7461b5555912088a1a", // 申请好的Web端开发者Key，首次调用 load 时必填
                    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                    plugins
                }).then((AMap) => {
                    let map = new AMap.Map("MapContainer", initMap);
                    // 设置地图鼠标样式
                    map.setDefaultCursor("pointer");
                    this.map = map;
                    // 插件初始化：
                    // 1.3D地图方向调节
                    if (plugins?.includes('AMap.Geocoder')) {
                        // 定义逆地址编码
                        this.geocoder = new AMap.Geocoder({
                            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                            city: "全国",
                        });
                    }
                    if (plugins?.includes("AMap.ControlBar")) {
                        map.addControl(new AMap.ControlBar({}));
                    }
                    // 定义菜单实例
                    this.contextMenu = new AMap.ContextMenu();
                    // 定义信息窗体
                    this.infoWindow = new AMap.InfoWindow({
                        offset: new AMap.Pixel(0, -30),
                    });
                    resolve(true);
                }).catch((e) => {
                    // this.$Notify('地图加载失败!', e);
                    resolve(false);
                });
            })

        },
        // 获取指定的标记
        getA_Type(type) {
            return this.map.getAllOverlays(type);
        },
        // 增加折线
        addPolyline(config, styleName) {
            console.log(styleName);
            const polyline = new AMap.Polyline(this[styleName]); //获取折线配置并且生成折线实例
            polyline.setOptions({
                ...config
            });
            this.map.add(polyline); //添加入地图
            return polyline
        },
        // 增加圆形
        addCircle(config, styleName) {
            let { options, showInfo, content } = config;
            const circle = new AMap.Circle(this[styleName]); //获取折线配置并且生成折线实例
            circle.setOptions({
                ...options
            });
            if (showInfo) {
                //设定信息窗口
                circle.content = content || '空';
                //添加点击出现信息窗口事件
                circle.on("click", this.markerClick);
            }
            this.map.add(circle); //添加入地图
            return circle;
        },
        // 往地图上批量添加点标记
        addMarker(markers = []) {
            if (markers.length === 0) {
                console.warn('未传入标记变量!')
                return false;
            };
            let { markerType } = this;
            markers.forEach(item => {
                let { showInfo = false, content, icon = 'blue', options } = item;
                let marker = new AMap.Marker({
                    anchor: "bottom-center",
                    zIndex: 10,
                    ...options,
                    icon: markerType[icon]
                });
                if (showInfo) {
                    //设定信息窗口
                    marker.content = content || '空';
                    //添加点击出现信息窗口事件
                    marker.on("click", this.markerClick);
                }
                this.map.add(marker);
            })
        },
        // 获取信息窗体
        getInfoWindow(options) {
            return new AMap.InfoWindow(options);
        },
        // 获取热力图实例
        getHeatMap(options) {
            return new AMap.HeatMap(this.map, options)
        },
        // 逆地理编码地址[longitude, latitude]
        useGeocoder(lnglat) {
            if (this.geocoder) {
                return new Promise((res, rej) => {
                    this.geocoder.getAddress(lnglat, function (status, result) {
                        if (status === "complete" && result.regeocode) {
                            res(result.regeocode.formattedAddress)
                        } else rej(false)
                    });
                })
            } else {
                return false;
            }
        },
        // 点击锚点标记出现信息窗口
        markerClick(e) {
            this.infoWindow.setContent(e.target.content);
            this.infoWindow.open(this.map, e.target.getPosition());
        },
        // 清空地图上所有标记
        clear(able) {
            this.map.clearMap();
            if (able === 'note') {
                this.$Notify('已清空所有标记!');
            }

        },
        // 调整视角
        fitView() {
            this.map.setFitView();
        },
        // 地图销毁
        destroy() {
            let { map } = this;
            map && map.destroy();
        }
    }
}
</script>
<style scoped lang="less">
/deep/ .amap-marker,
/deep/ .amap-icon,
/deep/ .amap-icon img {
    width: 32px !important;
    height: 32px !important;
}

.map-view {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

#MapContainer {
    flex: 1;
    padding: 0px;
    margin: 0px;
    box-sizing: border-box;
    border: 2px solid #f1f4f7;
    border-radius: 10px;
    width: 100%;
}
</style>